<template>
  <div class="game_home">
    <!-- header -->
    <div v-if="hideHeaderAndFooter" class="game_header">
      <div class="game_header_content gl_clear">
        <div class="game_header_title gl_fl">
          <span v-if="gameId" class="game_info_title" @click="goGameInfo">{{ homeLinkeTitle }}</span>
        </div>
        <div class="game_header_login gl_fr">
          <span v-if="!tokenInfo" @click="goLogin">登录 | 注册</span>
          <template v-if="tokenInfo">
            <!-- 机构切换 -->
            <template v-if="ouList.length && ouList.length > 1 && isRouteInMycnter">
              <el-dropdown class="right-menu-item gl_mr_20" @command="changeOU">
                <span style="cursor: pointer" class="el-dropdown-link nav_name">
                  {{ currentOU.displayName }}<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="(item, index) in ouList" :key="index" :command="item">
                    <span :class="{'activeOU': item._isActive}">{{ item.displayName }}</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <!-- 跳转 -->
            <el-dropdown class="avatar-container" trigger="click">
              <div class="avatar-wrapper">
                <show-avatar
                  :src="getStaticAvatarUrl(currentUserIndInfo && currentUserIndInfo.imagePath)"
                  width="36px"
                  height="36px"
                  shape="circle"
                />
                <span class="username">{{ info && info.phoneNumber }}</span>
                <i class="el-icon-caret-bottom" style="color: #fff;" />
              </div>
              <el-dropdown-menu slot="dropdown" class="user-dropdown">
                <el-dropdown-item v-if="showSysManagementPage" @click.native="toSysManagementPage">
                  <span style="display:block;">跳转到后台</span>
                </el-dropdown-item>
                <el-dropdown-item v-if="ouEdition" @click.native="toSysHallPage">
                  <span style="display:block;">跳转到道馆</span>
                </el-dropdown-item>
                <el-dropdown-item @click.native="toMyCenter">
                  <span style="display:block;">个人中心</span>
                </el-dropdown-item>
                <el-dropdown-item @click.native="logoutConfirm">
                  <span style="display:block;">退出</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </div>
        <div class="game_header_download gl_fr">
          <span class="qrcode_text">下载TKD大满贯APP</span>
          <div class="qrcode_content">
            <div class="qrcode_item">
              <div id="qrcode_android" class="qrcode_android" />
              <div class="qrcode_title">Android 下载</div>
            </div>
            <!-- <div class="qrcode_item">
              <div class="qrcode_ios">1</div>
              <div class="qrcode_title">iPhone 下载</div>
            </div> -->
          </div>
        </div>
      </div>
    </div>

    <!-- router-view -->
    <div class="main_router_view">
      <router-view />
    </div>

    <!-- bottom -->
    <div v-if="hideHeaderAndFooter" class="game_footer">
      <div class="game_footer_content">
        <el-row style="border-bottom: 1px solid #fff;padding: 70px 0 40px;">
          <el-col :span="4">
            <img class="game_footer_logo" src="../../assets/images/logo/logo_white.png" alt="" srcset="">
          </el-col>
          <el-col :span="20" align="right">
            <div class="gl_clear">
              <ul class="game_footer_link gl_fr">
                <li class="game_footer_linkItem gl_fl" @click="goGameInfo">
                  <div>
                    <img class="game_footer_linkImg" src="../../assets/images/goHome.png" alt="" srcset="">
                  </div>
                  <div>回到{{ homeLinkeTitle }}</div>
                </li>
                <li class="game_footer_linkItem gl_fl" @click="jumpToUrl('https://www.wtwuxicenter.com/')">
                  <div>
                    <img class="game_footer_linkImg" src="../../assets/images/goCenter.png" alt="" srcset="">
                  </div>
                  <div>回到无锡中心</div>
                </li>
              </ul>
            </div>
          </el-col>
        </el-row>
        <el-row class="gl_py_20">
          <el-col :span="12">
            版权所有 © {{ copyright }}
          </el-col>
          <el-col :span="12" align="right">
            <a :href="archivalUrl">苏ICP备{{ archival }}号</a>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { getToken } from '@/lib/auth';
import { judgeToLogout, loginOidc } from '@/lib/oidc_fun';
import { api_GET_UsersOrganizationUnit } from '@/extend/api/swaggerApi/identity';
import { api_GET_EventsManagementRegisterId } from '@/extend/api/gameswaggerApi/app';

import {
  api_GET_UsersPemissionOrganizationUnits // 获取组织机构列表
} from '@/extend/api/swaggerApi/identity.js';
import QRCode from 'qrcodejs2';
export default {
  data() {
    return {
      gameId: '',
      showSysManagementPage: false,
      ouList: [] // 机构列表
    };
  },
  computed: {
    ...mapState({
      archival: state => state.app.archival,
      archivalUrl: state => state.app.archivalUrl,
      copyright: state => state.app.copyright,
      copyrightUrl: state => state.app.copyrightUrl,
      currentUserType: state => state.user.currentUserType,
      currentUserIndInfo: state => state.user.currentUserIndInfo,
      info: state => state.user.info,
      tokenInfo: state => state.user.token || getToken()
    }),
    blankPagePre() {
      return window.location.origin + '/game.html#/';
    },
    sysManagementPage() {
      return window.location.origin;
    },
    sysHallPage() {
      return window.location.origin + '/hall.html#/t__' + (this.tenantId || '') + '/hall';
    },
    tenantId() {
      let tenantId = this.gameId
        ? this.gameId.lastIndexOf('_') > -1
          ? this.gameId.substring(this.gameId.lastIndexOf('_') + 1)
          : ''
        : '';
      tenantId = tenantId || this.$route.query.tenantid;
      return tenantId;
    },
    homeLinkeTitle () {
      const _name = this.$route.name;
      let _showName = '首页';
      switch (_name) {
        case 'TrainDetail':
          _showName = '培训首页';
          break;
        case 'GameInfo':
          _showName = '赛事首页';
          break;
        default:
          _showName = '首页';
          break;
      }

      return _showName;
    },
    hideHeaderAndFooter () {
      const _routeNameMap = {
        'Message': 'Message', // 消息不显示头尾
        'MessageList': 'MessageList',
        'MessageH5': 'MessageH5',
        'MessageType': 'MessageType',
        'MessageH5CheckIn': 'MessageH5CheckIn',
        'MessageH5CheckOut': 'MessageH5CheckOut',
        'MessageH5StudentReport': 'MessageH5StudentReport',
        'MessageH5StudentReportPersonInfo': 'MessageH5StudentReportPersonInfo',
        'MessageH5StudentReportGameInfo': 'MessageH5StudentReportGameInfo',
        'MessageH5StudentReportTrainInfo': 'MessageH5StudentReportTrainInfo',
        'MessageH5StudentReportDeclareInfo': 'MessageH5StudentReportDeclareInfo'
      };
      const _routeName = this.$route.name;
      const _title = this.$router.history.current.meta.title;
      if (_title === 'integral') {
        return false;
      }

      // 如果路由名存在于需要隐藏头尾的列表中，则隐藏
      if (_routeName in _routeNameMap) {
        return false;
      }

      return true;
    },
    currentOUid () {
      return this.$store.state.user.currentOU;
    },
    currentOU () {
      return this.ouList.find(item => item.id === this.currentOUid) || {};
    },
    // 路由是否存在于mycenter中
    isRouteInMycnter () {
      const _path = this.$route.fullPath;
      return _path.indexOf('myCenter') !== -1;
    },
    currentUserInfo () {
      return this.$store.state.user.info || {};
    },
    ouEdition () {
      const _ouEdition = this.currentUserInfo.organizationUnitEdition;
      return _ouEdition;
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler() {
        this.gameId = this.$route.params.id;
      }
    },
    currentUserType: {
      handler(val) {
        if (!val) return;
        this.handleShowBtnWithSys();
        this.getIndividualInfo();
      }
    }
  },
  created() {
    this.showSysManagementPage = false;
    if (this.currentUserType) {
      this.handleShowBtnWithSys();
      this.getIndividualInfo();
      this.getOuList();
    }
  },
  mounted() {
    this.createCode();
  },
  methods: {
    jumpToUrl (url) {
      var a = document.createElement('a');
      var event = new MouseEvent('click');
      a.href = url;
      a.target = '_blank';
      a.dispatchEvent(event);
    },
    // 处理显示后台跳转按钮显示
    async handleShowBtnWithSys() {
      this.showSysManagementPage = false;
      if (this.currentUserType && 'delegationId' in this.currentUserType) {
        const _delegationId = this.currentUserType.delegationId;
        if (_delegationId && this.getManageSysIdentity()) {
          this.showSysManagementPage = true;
        }
      }
    },
    getManageSysIdentity() {
      // const identityList = [
      //   'AbpIdentity',
      //   'EventsManagement.Competitions',
      //   'Order',
      //   'GameManage',
      //   'Logistics.Default',
      //   'Train.Trainnings',
      //   'Mall.Store',
      //   'Club.Management'
      // ];
      // const _info = this.info;
      // for (const i in identityList) {
      //   if (_info.permissions.includes(identityList[i])) {
      //     return true;
      //   }
      // }
      const _info = this.info;

      // 如果用户被禁用，则有权限但无法进入后台及道馆，屏蔽掉入口
      if (_info.currentOrganizationUnit === null && _info.currentOrganizationUnitId === null) {
        return false;
      }

      if (_info.permissions && _info.permissions.length > 0) {
        return true;
      }
      return false;
    },
    // 头像回显
    getStaticAvatarUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    getCurrentOrg() {
      return new Promise((resolve, reject) => {
        api_GET_UsersOrganizationUnit().then(res => {
          resolve(res);
        }, error => {
          reject(error);
        });
      });
    },
    goGameInfo() {
      if (this.gameId) {
        this.$router.push({
          path: `/home/${this.gameId}`
        });
      }
    },
    goLogin() {
      let tenantId = this.tenantId ? this.tenantId : '';
      tenantId = tenantId + '___' + ENVIR;
      let href = window.location.href;
      href =
        href.indexOf('#') > -1
          ? href.indexOf('?') > -1
            ? href + '&'
            : href + '?'
          : href + '#/?';
      href = href
        .replace(/loginRandom=[0-9]+|loginRandom=/g, '')
        .replace(/&&+/g, '&')
        .replace('?&', '?');
      href = href + 'loginRandom=' + new Date().getTime();
      // 跳转登录
      loginOidc({
        state: window.btoa(href),
        acr_values: tenantId ? window.btoa(tenantId) : ''
      });
    },
    logoutConfirm() {
      this.$confirm('您确定退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.logout();
      });
    },
    async logout() {
      const tenantId = !(
        this.$route.params &&
        this.$route.params.id &&
        this.$route.params.id.lastIndexOf('_') > -1
      )
        ? this.$store.state.user.info && this.$store.state.user.info.tenantId
          ? this.$store.state.user.info.tenantId
          : ''
        : this.tenantId || '';
      await this.$store.dispatch('user/logout');
      // this.goLogin();
      let refs =
        window.location.href.indexOf('/myCenter') > -1
          ? window.location.origin + window.location.pathname + '#/myCenter'
          : window.location.href;
      refs =
        refs.indexOf('#') > -1
          ? refs.indexOf('?') > -1
            ? refs + '&'
            : refs + '?'
          : refs + '#/?';
      refs = refs
        .replace(/tenantid=[0-9a-z\-]+|tenantid=/g, '')
        .replace(/&&+/g, '&')
        .replace('?&', '?');
      judgeToLogout(refs + 'tenantid=' + tenantId);
      // this.tokenInfo = getToken();
    },
    toMyCenter() {
      window.open(this.blankPagePre + 'myCenter', '_blank');
    },
    toSysManagementPage() {
      window.open(this.sysManagementPage, '_blank');
    },
    toSysHallPage () {
      window.open(this.sysHallPage, '_blank');
    },
    getIndividualInfo() {
      return new Promise((resolve, reject) => {
        if (!this.currentUserType.registerId) return;
        this.personInfoLoading = true;
        api_GET_EventsManagementRegisterId(
          this.currentUserType.registerId,
          { IncludeGender: true, IncludeIdCardType: true }
        ).then(res => {
          this.$store.dispatch('user/getSaveCurrentUserIndInfo', res);
          resolve(res);
        }, error => {
          this.$message({ type: 'error', message: error.error && error.error.message || '' });
          reject(error);
        });
      });
    },
    getOuList () {
      api_GET_UsersPemissionOrganizationUnits()
        .then(
          res => {
            let _list = res || [];
            _list = _list.map(item => {
              item._isActive = item.id === this.currentOUid;
              return item;
            });
            this.ouList = _list;
          }
        )
        .catch(
          error => {
            this.$message({
              message: `版本列表获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    changeOU (val) {
      this.$store.dispatch('user/setCurrentOUID', val.id)
        .then(
          () => {
            window.location.href = window.location.origin + window.location.pathname + '#/myCenter/individual/info';
            window.location.reload(true);
          }
        );
    },
    // 生成二维码
    createCode() {
      new QRCode('qrcode_android', {
        width: 88,
        height: 88,
        text: 'https://file.wtwuxicenter.com/upload/app/0823113321.apk'
      });
    }
  }
};
</script>

<style scoped>
.game_header_title{
  padding-left: 40px;
}
.game_header_login{
  padding-right: 40px;
}
.game_header_download{
  position: relative;
  padding-right: 50px;
  font-size: 14px;
  color: #e6ecf0;
  cursor: pointer;
}
.game_header {
  width: 100%;
  min-width: 1200px;
  height: 60px;
  background-color: #31456c;
}
.game_footer {
  width: 100%;
  min-width: 1200px;
  background-color: #31456c;
}
.game_header_content,
.game_footer_content {
  width: 1200px;
  margin: 0 auto;
  color: #fff;
}
.game_header_content {
  line-height: 60px;
  font-size: 16px;
}
.game_footer_content {
  font-size: 15px;
}
.game_footer_logo {
  height: 64px;
  vertical-align: middle;
  margin-right: 35px;
}
.game_footer_link {
  text-align: center;
}
.game_footer_linkItem {
  margin-right: 40px;
  cursor: pointer;
}
.game_footer_linkImg {
  width: 38px;
  height: 38px;
  margin-bottom: 20px;
}
.game_header_login,
.game_info_title {
  cursor: pointer;
}
.main_router_view {
  box-sizing: border-box;
  margin-bottom: 30px;
  min-height: calc(100vh - 60px - 262px);
}
.archival_copyright {
  height: 60px;
  padding-top: 10px;
  line-height: 20px;
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.archival_copyright a {
  transition: all 0.3s ease;
}
.archival_copyright a:hover {
  text-decoration: underline;
}
.copyright img {
  vertical-align: middle;
  margin-right: 2px;
  width: 18px;
}
.footer_nav_item:hover {
  cursor: pointer;
  text-decoration: underline;
}
.game_header  .username {
  color: #fff;
  margin-left: 10px;
  line-height: initial;
}
.game_header .person_img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  vertical-align: middle;
}
.el-dropdown-menu__item {
  min-width: 110px;
}
.activeOU {
  color: #409eff
}
.right-menu-item {
  color: #fff;
}
.qrcode_content {
  background: #fff;
  display: none;
  /* left: -114px; */
  left: -10px;
  padding: 20px 0;
  position: absolute;
  text-align: center;
  top: 50px;
  /* width: 316px; */
  width: 150px;
  -webkit-box-shadow: 0 2px 10px 0 hsl(0deg 0% 66% / 30%);
  box-shadow: 0 2px 10px 0 hsl(0deg 0% 66% / 30%);
  border-radius: 4px;
  z-index: 5;
  line-height: 0;
}
.qrcode_content:before {
  content: "";
  display: inline-block;
  position: absolute;
  top: -5px;
  /* left: 153px; */
  left: 70px;
  width: 10px;
  height: 10px;
  background: #fff;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
  z-index: 5;
}
.game_header_download:hover .qrcode_content {
  display: block;
}
/* .qrcode_item:first-child {
  border-right: 1px dashed #e8ebf3;
} */
.qrcode_item {
  display: inline-block;
  /* width: 50%; */
  width: 100%;
  font-size: 0;
  text-align: center;
}
.qrcode_android,
.qrcode_ios {
  display: inline-block;
  width: 88px;
  height: 88px;
}
.qrcode_title {
  margin-top: 8px;
  font-size: 14px;
  color: #141933;
  text-align: center;
  line-height: 20px;
}
</style>
